<?php

/**
 * 密码加密函数
 */
if (!function_exists("encryptPassword")){
    function encryptPassword($data)
    {
        $salt = "123123asdasdasd";
        $psw = md5($salt . md5($data));
        return $psw;
    }
}

/**
 * 通用响应
 * @params int code 响应码
 * @params string $msg 响应描述
 * @params string $data 响应数据
 */
function responseJson($code = 200, $msg = "success", $data = array())
{
    $res = array('code' => $code, 'msg' => $msg, 'data' => $data);
    echo json_encode($res);
    die;
}

/**
 * 成功响应
 * @params string $msg 响应描述
 * @params string $data 响应数据
 */
function success($data = array(), $msg = "success", $code = 200)
{
    responseJson($code, $msg, $data);
}

/**
 * 失败响应
 * @params string $msg 响应描述
 * @params string $data 响应数据
 */
function fail($code = 500, $msg = "fail")
{
    responseJson($code, $msg);
}

function responseArray($data)
{
    echo json_encode($data);
    die;
}
/**
 * 过滤特殊字符
 * @params string $strParam 需要过滤字符串
 */
function replace_specialChar($strParam)
{
    $regex = "/\/|\～|\，|\。|\！|\？|\“|\”|\【|\】|\『|\』|\：|\；|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
    return preg_replace($regex, "", $strParam);
}

//发送curl请求函数
if (!function_exists('curl_request')) {
    function curl_request($url, $post = true, $params = array(), $https = true)
    {
        //初始化请求会话
        $ch = curl_init($url);
        if ($post) {
            //设置请求方式为post
            curl_setopt($ch, CURLOPT_POST, true);
            //设置请求参数
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        if ($https) {
            //如果是https协议，禁止服务器验证本地证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        //发送请求，获取返回参数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        //关闭请求
        curl_close($ch);
        return $res;
    }
}


/*
 * 随机位数验证码
 */

if (!function_exists('rand_code')) {
    function rand_code($num)
    {
        $code = '';
        for ($i = 0; $i < $num; $i++) {
            $code .= mt_rand(1, 9);
        }
        return $code;
    }
}
/*
 * 验证手机号码是否正确
 */
if (!function_exists('validate_phone')) {
    function validate_phone($phone)
    {
        $rules = "/^1[34578]\d{9}$/";
        return preg_match($rules, $phone);
    }
}

/*
 * 发送短信接口
 */
if (!function_exists('send_msg')) {
    function send_msg($phone, $msg)
    {
        $app_key = config_item('msg_app_key');
        $url = config_item('msg_url');
        $sign = config_item('sign');
        $content = "您的本次的验证码是：" . $msg . "。";
        $url = $url . '?sign=' . $sign . '&mobile=' . $phone . '&content=' . $content . '&appkey=' . $app_key;
        //需要打开
        //$data = curl_request($url,false);
        //$data = json_decode($data,true);
        //$data['code'] == 10000 ? $status = true : $status =false;
        //测试(需要关闭)
        $status = true;
        return $status;
    }
}

/*
 * 图片上传
 */

if (!function_exists('imgUpload')) {
    function imgUpload($name = "img",$type)
    {
        $data = $_FILES;
        $allows = ['image/gif', 'image/png', 'image/jpg', 'image/jpeg'];
        if (!in_array($data[$name]['type'], $allows)) {
            return false;
        }
        //从文件名中获取文件类型
        $fileTypeArray = explode('.', $data[$name]['name']);
        $fileType = $fileTypeArray[count($fileTypeArray) - 1];
        //设置图片上传的路径
        $filePath = "uploads/{$type}/" . date('Ymd') . '/';

        //没有就创建文件夹
        if (!file_exists($filePath)) {
            //递归创建
            mkdir($filePath, 0755,true);
        }
        //存储的文件名
        $fileName = time() . rand(1000, 9999);
        $file = $filePath . $fileName . '.' . $fileType;
        $res = move_uploaded_file($data[$name]['tmp_name'], $file);
        if ($res) {
            return $file;
        }
        return false;
    }
}

//计算概率 [$index=>$rate] $rate为概率，$index,返回中奖的物品
if (!function_exists('rateGetAward')) {
    function rateGetAward($data)
    {
        $sum = array_sum($data);
        //概率不足100补全100，考虑的是单个奖品中奖的概率
        if ($sum < 100){
            $sum = 100;
        }
        $index = rand(1, $sum);
        $min = 1;
        foreach ($data as $k => $v) {
            $max = $min + $v;
            if ($index >= $min && $index < $max) {
                return $k;
            }
            $min = $max;
        }
        //false就是未中奖
        return false;
    }
}

//敏感词检测三方
if (!function_exists("checkTxt")) {
    function checkTxt($txt)
    {
        $appKey = config_item('msg_app_key');
        $url = config_item('char_url');
        $url = $url . "?content={$txt}&appkey={$appKey}";
//        $res = curl_request($url, false);
        //测试使用
        $res = "{\"code\":\"10000\",\"charge\":false,\"remain\":0,\"msg\":\"查询成功\",\"result\":{\"showapi_res_error\":\"\",\"showapi_res_id\":\"6191fddb0de376ab373ef3e8\",\"showapi_res_code\":0,\"showapi_fee_num\":1,\"showapi_res_body\":{\"ret_code\":\"0\",\"remark\":\"检测成功\",\"labels\":[{\"rate\":100.0,\"sug\":\"pass\",\"msg\":\"存在低俗辱骂不合规\",\"words\":[\"傻逼\"],\"label\":\"abuse\"}],\"content\":\"傻逼\"}},\"requestId\":\"b359f04c43bf438a965fb69858646338\"}";
        $res = json_decode($res, true);
        $response = [
            'code' => 200,
            'status' => true,
            'msg' => '检测成功'
        ];
        $result = $res['result']['showapi_res_body'];
        //请求发送是否成功
        if ($res['code'] != 10000) {
            $response = [
                'code' => $res['code'],
                'status' => false,
                'msg' => $res['msg']
            ];
        } else if ($result['ret_code'] != 0) {
            //查看本次接口检测是否成功
            $response = [
                'code' => 400,
                'status' => false,
                'msg' => '接口调用失败!'
            ];
        } else if ($result['labels'][0]['sug'] != 'pass') {
            //检测词汇是否通过
            $response = [
                'code' => 200,
                'status' => false,
                'msg' => $result['labels'][0]['msg'],
            ];
        }
        return $response;
    }
}

//批量上传图片
if (!function_exists("uploadImages")) {
    function uploadImages($name = 'img', $dir = '')
    {
        $files = $_FILES[$name];
        if (!$files) {
            return false;
        }
        if (!is_array($files['name'])) {
            imgUpload($name);
        }
        //若没有传递上传目录则为默认目录
        if ($dir == '') {
            $dir = 'static/img/' . date('Y-m-d', time());
        }
        if (!file_exists($dir)) {
            mkdir($dir, 0755,true);
        }
        //图片上传总数
        $count = count($files['name']);
        //允许上传的图片类型
        $allowType = ['image/gif', 'image/png', 'image/jpg', 'image/jpeg'];
        $file = [];
        for ($i = 0; $i < $count; $i++) {
            $nameItem = $files['name'][$i];
            $tmpItem = $files['tmp_name'][$i];
            //图片类型
            $typeItem = $files['type'][$i];
            //图片是否符合类型
            if (!in_array($typeItem, $allowType)) {
                return false;
            }
            //获取图片后缀
            $fileTypeArray = explode('.', $nameItem);
            $fileType = $fileTypeArray[count($fileTypeArray) - 1];
            $uploadName = $dir . '/' . time() . rand(1000, 9999) . '.' . $fileType;
            $res = move_uploaded_file($tmpItem, $uploadName);
            if (!$res) {
                return false;
            }
            $file[] = $uploadName;
        }
        return $file;
    }
}

//生成随机中文字符
if (!function_exists('getChar')){
    function getChar($num)  // $num为生成汉字的数量
    {
        $b = '';
        for ($i=0; $i<$num; $i++) {
            // 使用chr()函数拼接双字节汉字，前一个chr()为高位字节，后一个为低位字节
            $a = chr(mt_rand(0xB0,0xD0)).chr(mt_rand(0xA1, 0xF0));
            // 转码
            $b .= iconv('GB2312', 'UTF-8', $a);
        }
        return $b;
    }
}

//随机生成n条手机号
if (!function_exists('getRandomMobile')) {
    function getRandomMobile($num = 1)
    {
        //前三位
        $tel_arr = array(
            '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '144', '147', '150', '151', '152', '153', '155', '156', '157', '158', '159', '176', '177', '178', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189',
        );
        if ($num == 1){
            $phone = $tel_arr[array_rand($tel_arr)] . mt_rand(1000, 9999) . mt_rand(1000, 9999);
            return $phone;
        }else{
            for ($i = 0; $i < $num; $i++) {
                //随机前三位加上两个随机的1000-9999
                $phone[] = $tel_arr[array_rand($tel_arr)] . mt_rand(1000, 9999) . mt_rand(1000, 9999);
            }
            //去除重复的号码
            return array_unique($phone);
        }
    }
}

/**
 * 获得随机字符串
 * @param $len             需要的长度
 * @param $special        是否需要特殊符号
 * @return string       返回随机字符串
 */
if (!function_exists('getRandomStr')) {
    function getRandomStr($len, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}